package com.dc.bobaoge.project.v3.to.v2.business.core.util;

import com.dc.bobaoge.common.base.BaseOrderNumber;
import com.dc.bobaoge.common.em.OrderNumberEnum;
import com.own.component.common.exception.BusinessSimpleException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * OrderGenerateUtil
 * <p>
 * 订单号生成工具（32位订单号）
 *
 * @author chenxueli
 * @date 2023-06-05 14:26:00
 */
@Slf4j
@Component
public class OrderGenerateUtil {

    private static final List<BaseOrderNumber> BILL_SHOW_TYPE_LIST = new ArrayList<>();
    private static final Map<String, BaseOrderNumber> BILL_SHOW_TYPE_MAP = new HashMap<>();

    static {
        BILL_SHOW_TYPE_LIST.addAll(Arrays.asList(OrderNumberEnum.Pay.values()));
        BILL_SHOW_TYPE_LIST.addAll(Arrays.asList(OrderNumberEnum.Income.values()));
        BILL_SHOW_TYPE_LIST.addAll(Arrays.asList(OrderNumberEnum.Refund.values()));
        BILL_SHOW_TYPE_LIST.forEach(item -> BILL_SHOW_TYPE_MAP.put(item.category(), item));
    }

    /**
     * 解析订单号
     *
     * @param orderNo 订单号信息
     * @return 解析后的数据
     */
    public static BaseOrderNumber resolve(String orderNo) {
        if (StringUtils.isBlank(orderNo) || orderNo.length() < 5) {
            throw new BusinessSimpleException("订单解析数据异常");
        }
        var sign = orderNo.substring(3, 5);
        var em = BILL_SHOW_TYPE_MAP.get(sign);
        if (em == null) {
            throw new BusinessSimpleException("订单解析数据异常");
        }
        return em;
    }

    /**
     * 解析订单号
     *
     * @param orderNo 订单号信息
     * @return 解析后的数据
     */
    public static BaseOrderNumber resolveNoCheck(String orderNo) {
        try {
            return resolve(orderNo);
        } catch (Exception e) {
            log.error("订单解析数据异常", e);
            return null;
        }
    }

}
